package org.javaymw.springboot.base.session;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

/**
 * 本地session
 */
@Component
public class HttpSessionProvider implements SessionProvider {

    @Override
    public void setAttribute(HttpServletRequest request, String name, Serializable value) {
        /**
         * getSession()和getSession(boolean create)的区别
         * 1.getSession()默认有session的值就直接返回，没有就重新创建一个session对象
         */
        HttpSession session = request.getSession();//true Cookie JSESSIONID
        session.setAttribute(name, value);
    }

    public Serializable getAttribute(HttpServletRequest request, String name) {
        HttpSession session = request.getSession(false);
        if(session != null){
            return (Serializable) session.getAttribute(name);
        }
        return null;
    }

    public void logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session != null){
            session.invalidate();//失效
        }
        //Cookie JSESSIONID
    }

    public String getSessionId(HttpServletRequest request) {
        //获取url上的sessionId
        //request.getRequestedSessionId();//Http://localhost:8080/html/sfsf.shtml?JSESSIONID=asldfjsf234
        return request.getSession().getId();
    }
}
